<template>
  <div class="active">
    <h3>项目评审结果</h3>
    <!-- 项目评审结果 -->
    <el-table
      :data="projectReviews"
      stripe
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        prop="key"
        label="序号"
        width="81"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="applyTime"
        label="报名时间"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplierCode"
        label="供应商编码"
        width="200"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="报名供应商"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="status"
        label="资质审查"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="price"
        label="报价"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="reviewResult"
        label="评审结果"
        width="100"
        align="center"
      ></el-table-column>
    </el-table>
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <h3>中选供应商结果确认</h3>
      <el-button type="primary" @click="getInfo(true)">刷新</el-button>
    </div>
    <el-form :model="SelectedForm" label-width="250px">
      <div v-if="OverStatus == 'continue'">
        <el-form-item label="中选供应商：" v-if="Previous != 'vieTaskExamine'">
          <el-select
            @change="editform('outbidOneId')"
            v-model="SelectedForm.outbidOneId"
            placeholder="请选择中选供应商"
            style="width: 500px"
          >
            <el-option
              v-for="candidate in candidates"
              :key="candidate.id"
              :label="candidate.name"
              :value="candidate.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="中选理由：" v-if="Previous != 'vieTaskExamine'">
          <el-input
            @blur="editform"
            type="textarea"
            placeholder="请输入中选供应商中选理由"
            style="width: 500px"
            v-model="SelectedForm.remarkOne"
          ></el-input>
        </el-form-item>
        <el-form-item label="中选理由：" v-else>
          <el-input
            @blur="editform"
            type="textarea"
            placeholder="请输入中选供应商中选理由"
            style="width: 500px"
            v-model="SelectedForm.remarkOne"
          ></el-input>
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item label="强制终止评审原因：">
          <el-input
            placeholder="请输入强制终止原因"
            @blur="editform"
            style="width: 500px"
            v-model="SelectedForm.breakRemark"
          ></el-input>
        </el-form-item>
      </div>
      <el-form-item :label="`主持人(${hostname})签名确认结果时间：`">
        <el-input
          style="width: 500px"
          v-model="SelectedForm.restartCheck.restartCheckTime"
          placeholder="请主持人签名"
          disabled
        ></el-input>
        <span class="link" @click="StartSingin(hostid)"
          >主持评审结果确认签名</span
        >
      </el-form-item>
      <el-form-item :label="`主持人(${hostname})评审结果确认签名：`">
        <div class="tablet">
          <el-image
            v-if="SelectedForm.restartCheck.restartCheck"
            :src="baseURL + SelectedForm.restartCheck.restartCheck"
          >
            <template #error>
              <div class="image-slot"></div>
            </template>
          </el-image>
        </div>
      </el-form-item>
      <el-form-item
        :label="`辅助主持人${index + 1}(${item.name})评审签到签名：`"
        v-for="(item, index) in SelectedForm.Signlist"
        :key="index"
      >
        <div class="tablet">
          <el-image v-if="item.restartCheck" :src="baseURL + item.restartCheck">
            <template #error>
              <div class="image-slot"></div>
            </template>
          </el-image>
        </div>
        <span class="link" @click="StartSingin(item.id)"
          >辅助主持人{{ index + 1 }}签到签名</span
        >
      </el-form-item>
      <sxb ref="Tablet" @Return="Return" style="display: none" />
      <div
        class="endbutton"
        v-if="Previous == 'vieTaskResultBreak' || Previous == 'vieTaskBreak'"
      >
        <el-button @click="prevPage">上一步</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
      <div class="endbutton" v-else>
        <el-button @click="prevPage">上一步</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button type="danger" @click="terminate">强制中止</el-button>
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import {
  projectInfoAndSupplierAndJudge,
  vieAuditchoiceSupplier,
  vieAuditSign,
  vieAuditqueryTaskId,
  vieAuditexecTask,
  selectMc,
  vieAuditselectResultStatus,
} from "@/api/examine.js";
import { ElMessage } from "element-plus";

const emit = defineEmits(["next-step"]);
import sxb from "@/components/sxb.vue";
const route = useRoute();
const id = computed(() => route.query.id);
const judgeId = ref("");
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
});
const userInfo = computed(() => JSON.parse(localStorage.getItem("judgeInfo")));
const Tablet = ref(null);
// 定义数据
const SelectedForm = ref({
  outbidOneId: "",
  remarkOne: "",
  outbidTwoId: "",
  remarkTwo: "",
  outbidThreeId: "",
  remarkThree: "",
  restartCheckTime: "",
  restartCheck: "",
  Signlist: [],
  supervisorSignature: "",
});
const hostname = ref("");
const hostid = ref("");
const supervisename = ref("");
const baseURL = import.meta.env.VITE_APP_BASE_API;
const Stop = ref(false);
const supplierReviews = ref([]);
const projectReviews = ref([]);
const OverStatus = ref("");
const OverType = ref(false);
const stopbuttom = ref(true);
const candidates = ref([]);
const projectInfo = ref({});
const judgeList = ref([]);
const mainId = ref("");
const editform = () => {
  const params = {
    id: id.value,
    oaCode: projectInfo.value.oaCode,
    outbidOneId: SelectedForm.value.outbidOneId,
    outbidTwoId: SelectedForm.value.outbidTwoId,
    outbidThreeId: SelectedForm.value.outbidThreeId,
    remarkOne: SelectedForm.value.remarkOne,
    remarkTwo: SelectedForm.value.remarkTwo,
    remarkThree: SelectedForm.value.remarkThree,
    breakRemark: SelectedForm.value.breakRemark,
  };
  vieAuditchoiceSupplier(params).then((res) => {
    if (res.code == "200") {
      getInfo();
    }
  });
};
const submit = () => {
  const param = { projectId: id.value, execStatus: "continue" };
  vieAuditexecTask(param).then((res) => {
    if (res.code) {
      window.location.reload();
    }
  });
};
const terminate = () => {
  const param = { projectId: id.value, execStatus: "break" };
  vieAuditexecTask(param).then((res) => {
    if (res.code) {
      window.location.reload("");
    }
  });
};
const getInfo = (boolean) => {
  selectMc(id.value).then((res) => {
    if (res.code == "200") {
      mainId.value = res.data;
    }
  });
  SelectedForm.value = {
    outbidOneId: "",
    remarkOne: "",
    outbidTwoId: "",
    remarkTwo: "",
    outbidThreeId: "",
    remarkThree: "",
    restartCheckTime: "",
    restartCheck: "",
    Signlist: [],
    supervisorSignature: "",
  };
  try {
    projectInfoAndSupplierAndJudge({ id: id.value }).then((res) => {
      if (res.code == "200") {
        candidates.value = [];
        judgeList.value = res.data.judgeList;
        projectReviews.value = [];
        SelectedForm.value.outbidOneId = res.data.outbidOneId;
        SelectedForm.value.remarkOne = res.data.remarkOne;
        SelectedForm.value.breakRemark = res.data.breakRemark;

        for (let i = 0; i < res.data.judgeList.length; i++) {
          switch (res.data.judgeList[i].type) {
            case "judge_compere":
              if (res.data.judgeList[i].userId == mainId.value) {
                hostname.value = res.data.judgeList[i].name;
                hostid.value = res.data.judgeList[i].id;
                SelectedForm.value.restartCheck = {
                  id: res.data.judgeList[i].id,
                  restartCheck: res.data.judgeList[i].endCheck,
                  restartCheckTime: res.data.judgeList[i].endCheckTime,
                };
              } else {
                SelectedForm.value.Signlist.push({
                  id: res.data.judgeList[i].id,
                  restartCheck: res.data.judgeList[i].endCheck,
                  name: res.data.judgeList[i].name,
                });
              }
              break;
          }
        }
        candidates.value.push({
          id: "",
          name: "无",
        });
        let supplierList=[]
        for (let i = 0; i < res.data.supplierList.length; i++) {
          
        if(res.data.supplierList[i].status=='apply_supplier_pass'){
          supplierList.push(res.data.supplierList[i])
        }
        }
        // 首先根据价格对供应商列表进行排序，并复制到新的数组中
        let sortedSuppliers = [...supplierList].sort(
          (a, b) => a.price - b.price
        );

        // 获取最低价格
        let lowestPrice =
          sortedSuppliers.length > 0 ? sortedSuppliers[0].price : Infinity;

        // 定义最高可接受价格为最低价格的120%
        let maxAcceptablePrice = lowestPrice * 1.2;
        for (let i = 0; i < res.data.supplierList.length; i++) {
          let currentSupplierInSorted = sortedSuppliers.find(
            (supplier) =>
              supplier.supplierId === res.data.supplierList[i].supplierId
          );
          if (res.data.supplierList[i].status !== "apply_supplier_no_pass") {
            // 查找当前供应商在排序后的数组中的位置

            // 如果找到了供应商并且其价格在可接受范围内，则添加到 candidates.value
            if (
              currentSupplierInSorted &&
              currentSupplierInSorted.price < maxAcceptablePrice
            ) {
              candidates.value.push({
                id: res.data.supplierList[i].supplierId,
                name: res.data.supplierList[i].name,
              });
            }
          }
          const formattedDateTime = res.data.supplierList[i].applyTime.slice(
            0,
            16
          );
          let reviewResult = "";
          if (res.data.outbidOneId == res.data.supplierList[i].supplierId) {
            reviewResult = "中选";
          } else if (res.data.outbidOneId) {
            reviewResult = "落选";
          } else {
            reviewResult = "待定";
          }
          projectReviews.value.push({
            key: i + 1,
            applyTime: formattedDateTime,
            supplierCode: res.data.supplierList[i].supplierCode,
            name: res.data.supplierList[i].name,
            status:
              res.data.supplierList[i].status == "apply_supplier_pass"
                ? "符合"
                : "异常",
            price:
              currentSupplierInSorted &&
              currentSupplierInSorted.price < maxAcceptablePrice
                ? res.data.supplierList[i].price
                : res.data.supplierList[i].price
                ? `${res.data.supplierList[i].price}(超出差价)`
                : "/",
            reviewResult: reviewResult,
          });
        }
        if (boolean) {
          ElMessage({
            message: "刷新成功",
            type: "success",
          });
        }
      }
    });
  } catch (error) {}
  vieAuditselectResultStatus({ projectId: id.value }).then((res) => {
    if (res.code == "200") {
      OverStatus.value = res.data;
      OverType.value =
        (SelectedForm.value.breakRemark ||
          Previous.value == "vieTaskBreak" ||
          Previous.value == "vieTaskExamine") &&
        OverStatus.value != "continue";
    }
  });
};
const Return = (item) => {
  SelectedForm.value.restartCheck.restartCheck = item;
  const params = {
    projectId: id.value,
    projectCode: projectInfo.value.oaCode,
    projectJudgeId: judgeId.value,
    signStr: item,
    type: "sign_end",
  };
  vieAuditSign(params).then((res) => {
    if (res.code == "200") {
      getInfo();
    }
  });
};
const StartSingin = (id) => {
  judgeId.value = id;
  Tablet.value.beginSign();
};
const prevPage = () => {
  if (Stop.value) {
    (Stop.value = false), (SelectedForm.value.breakRemark = "");
  }
  emit("next-step", Previous.value);
};
const Previous = ref("");
onMounted(() => {
  getInfo();
  vieAuditqueryTaskId({ projectId: id.value }).then((res) => {
    Previous.value = res.data;
  });
});
</script>

<style scoped lang="scss">
@use "./judge";
:deep(.end th) {
  border: 1px solid transparent;
  border-top: 1px solid #06c;
}
:deep(.el-table thead.is-group th.el-table__cell) {
  background-color: #fff;
}
:deep(.el-form-item__content) {
  display: flex;
  align-items: start;
}
</style>
